package com.forsythia.sns;

import javax.sql.DataSource;

import com.forsythia.sns.TestCase;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BaseTestCase extends TestCase {
    
    private Logger log = Logger.getLogger(this.getClass());

    private DataSource dataSource;
    private ApplicationContext applicationContext;

    protected void setUp() throws Exception {
        super.setUp();
        applicationContext = new ClassPathXmlApplicationContext(getSpringApplicationContextClasspaths());
        dataSource = (DataSource) applicationContext.getBean(getDataSourceBeanId());
        runScripts();
    }
    
    protected void tearDown() throws Exception {
        super.tearDown();
    }

    protected ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    
    private void runScripts() {
        String[] scripts = getTestSQLScripts();
        if(scripts == null){
            return;
        }
        System.out.print("SQL scripts to initialize: ");
        for (int i = 0; i < scripts.length; i++) {
            if (i > 0) {
                System.out.print(", ");
            }
            System.out.print(scripts[i]);
        }
        System.out.print("\n");
        for (int i = 0; i < scripts.length; i++) {
            System.out.println("Running script: " + scripts[i]);
            runScript(scripts[i]);
        }
    }

    private void runScript(String resourcePath) {
//        Connection conn = null;
//        try {
//            
//        } catch (IOException e) {
//            log.error("Failed to load script: " + resourcePath + "Exception: " + e.getMessage());
//        } catch (SQLException e) {
//            log.error("Failed to load script: " + resourcePath + "Exception: " + e.getMessage());
//        } finally {
//            try {
//                conn.close();
//            } catch (Exception e) {
//                log.error("Exception when trying to colse connection.");
//            }
//        }
//        log.error("end");
    }
    
    /**
     * Need to rewrite almost time
     * @return String[]
     */
    protected String[] getSpringApplicationContextClasspaths(){
        log.warn("BaseTestCase.getSpringApplicationContextClasspaths()");
        log.warn("Using default application context config file: app-context-test.xml");
        return new String[] { "app-context-test.xml" };
    }
    
    protected String getDataSourceBeanId(){
        return "dataSource";
    }
    
    protected String[] getTestSQLScripts(){
        return null;
    }
    
    public void testTest(){
        
    }
}
